// pages/sita/chat/chat.js
var chatFun = require('../../fun_js/chat.js')
var mathFun = require('../../fun_js/math.js')
var goodsFun = require('../../fun_js/goods.js')
var recordFun = require('../../fun_js/record.js')
const CONTEXT = require('../../../utils/public_var.js')
const ocr = require('../../fun_js/ocr.js')
const app = getApp()
let query = null
var windowHeight = -1
var pixels =-1
var requestURL = ''
Page({
      /**
       * 页面的初始数据
       */

      data: {
        content:'',
        pageName:'',
        aiboid:'',
        fix_height: 0,
        whoAnswer:'rag',
        input_tx: '',
        intoViewName: 'endview',
        hideTip: true,
        isFree:'false',
        totalCount: 0,
        hints: {},
        ocrText: '',
        payCount: 0,
        MessageList: [],
        showCrop: true,
        animationData: {},
        bar_type: CONTEXT.TEXT_PAGE_TYPE,
        PAGETYPE: CONTEXT.IMG_PAGE_TYPE,
        TSXT_MSG: CONTEXT.TEXT,
        IMG_MSG: CONTEXT.IMAGE,
        funcSupport: {},
      },
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad(options) {
          //  this.data.aiboid = "LhjqCU*Kv1" 
           // this.initHomeData("LhjqCU*Kv1")
        this.getscene(options)
       
      },
      getscene(options) {
      
        if (options.scene != undefined) {
          const scene = decodeURIComponent(options.scene)
          var keyValue = scene.split('=');
          console.log(keyValue)
  
          // 创建一个对象，并以键值对的方式赋值
          var obj = {};
          obj[keyValue[0]] =keyValue[1];
          console.log(obj.aiboid)
          this.data.aiboid = obj.aiboid //obj.aiboid; // 获取属性值
          app.aibo.aibo_id = obj.aiboid
          this.initHomeData(obj.aiboid)
     
        }
      },
      initPage(itemData) {

        this.setData({
          bar_type: itemData.menuName,
          pageName:itemData.menuName,
          funcSupport: itemData.funcSupport,
          hideTip: itemData.hints == undefined ? true : false,
          hints: itemData.hints,
          isFree:itemData.isFree
        })
        requestURL = itemData.funCallURI
        wx.setNavigationBarTitle({
          title: itemData.menuName,
        })
        this.charBar_refresh(itemData)
      },
      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady() {

      },
      /**
       * 点击刷新按钮
       */
      charBar_refresh(data) {

        if (data.menuID == CONTEXT.IMG_PAGE_TYPE) {
          mathFun.initImgMsgData(this, data.welcomeIntro, app)
        } else {
          chatFun.initMsgData(this, data.welcomeIntro, app)
        }
      },
      showOpenTip() {
        wx.showModal({
          title: '',
          content: '我勤学苦练，\n每日更新,\n可删除并使用新版小程序',
          complete: (res) => {
            if (res.cancel) {

            }

            if (res.confirm) {

            }
          }
        })
      },

      inputChangetx: function (e) {
        chatFun.inputChangetx(this, app, e)
      },
      send_new_Msg(res) {
        console.log(res)
        if (res.detail.imgList.length > 0) {
          //还要判断是 OCR 还是图片识别
          if (res.detail.type == "OCR") {
            if (typeof (requestURL) == "undefined") {
              var sendMsg = {
                "role": 'user',
                "content": this.data.input_tx,
                "upImgUrl": res.detail.imgList[0],
                "msgtype": CONTEXT.TEXT
              }
              var data = {
                "role": 'system',
                "content": res.detail.msg,
                "msgtype": CONTEXT.TEXT
              }
              var list = this.data.MessageList
              list.push(sendMsg)
              list.push(data)
              this.setData({
                MessageList: list
              })
              this.setData({
                intoViewName: 'endview',
              })
              this.initSendUI();
              return
            }
            console.log("OCR")
            ocr.setORCText(app, this, res.detail.msg, res.detail.imgList[0], requestURL)

          } else if (res.detail.type == "Identifyingobjects") {
            // 图文
            goodsFun.sendImgTextMsg(this, res.detail.imgList[0], app, requestURL)
          }


        } else {
          if (this.data.bar_type == "翻译") {
            wx.showToast({
              title: '请上传要识别的图片',

              icon: 'error'
            })
            return
          }
          chatFun.sendTextMsg(this, app, requestURL)
        }
      },
      /**
       * OCR 识别成功后调用此方法
       * @param {} e 
       */
      // orcTextMsg(e){
      //   // ocr.setORCText(app,this,e.detail.data,requestURL)
      //   this.data.ocrText = e.detail.data
      // },
      sendUpImgMsg() {
        goodsFun.uploadImg(this, app)
      },

      /**
       * 生命周期函数--监听页面显示
       */
      onShow() {
        //获取小程序openID，和web过来的aibo di
        if (app.globalData.OpenID == "" || app.globalData.OpenID == undefined) {
          wx.showModal({
            title: '',
            content: '请您登录验证',
            confirmText: '登录',
            complete: (res) => {
              if (res.cancel) {
                setTimeout(()=>{
                  wx.navigateTo({
                    url: '/pages/login/atLogin/atLogin?aiboType='+'pay',
                  })
                },700)
              
              }
              if (res.confirm) {
                setTimeout(()=>{
                  wx.navigateTo({
                    url: '/pages/login/atLogin/atLogin?aiboType='+'pay',
                  })
                },700)
              }
            }
          })
        }
     
        
      },
      setScrollViewHeight(height) {
        var that = this
        if (windowHeight > 0) {
          this.initHeight(height)
        } else {
          wx.getSystemInfo({
            success: function (res) {

              windowHeight = res.windowHeight; // 获取页面可视区域的高度
              pixels = (10 * windowHeight) / 100;
              that.initHeight(height)
            }
          });
        }
      },
      initHeight(height) {

        var that = this
        that.setData({
          fix_height: windowHeight - height- pixels
        })
        setTimeout(() => {
          that.setData({
            intoViewName: 'endview'
          })
        }, 100)

      },
      getUseCount() {
        var that = this
        wx.request({
          url: app.app_url.BASE_URL + app.app_url.SITA_USE_COUNT,
          method: 'POST',
          data: {
            'openid': app.globalData.OpenID
          },
          success(res) {

            if (res.data.status == 400 || res.data.status == 200) {
              // that.data.totalCount = 100
              //  that.data.totalCount = res.data.total
              that.setData({
                totalCount: res.data.total
              })
            }
          },
          fail(res) {
            console.log(res)
          }

        })
      },
      bindList() {
        this.setData({
          showCrop: true
        })
        const child = this.selectComponent('#bottom');
        child.hintTip();
      },

      charBarInputLineChange(e) {

        var height = e.detail.data
        console.log(height)
        this.setScrollViewHeight(height)
      },
      /**
       * 上传图片
       */
      upload() {
        mathFun.upload(this, app)
      },
      /**
       * 剪裁图片
       */
      editImg() {
        mathFun.editImg(this, app, requestURL)

      },
      /**
       * 获取录音文件
       */
      getRecordFile(e) {
        console.log("获取录音文件");
        console.log(e);
        var text = e.detail.detail
        recordFun.ocrRequest(this, app, requestURL, text)
      },

      hintAll() {
        const child = this.selectComponent('#bottom');
        child.hintAll();
      },
      initSendUI() {
        const child = this.selectComponent('.bottom_class');
        child.initInputTx();
      },
      loadData() {
        return {
            "menuID": "101",
            "menuName": "Aiboss",
            "welcomeIntro": "您好，我的主人是Aibo，请问有什么可以帮你",
            "iconAddr": "https://genious.sitacloud.com/icon_imagee/101.svg",
            "promptString": "Enter your choice for Profile:",
            "funCallURI": "https://aibo.sitacloud.com/restful/wxmini/wxminiaskaibo/",
            "isFree": true,
            "funcSupport": {
              "textInput": {
                "available": "1",
                "iconAddr": "https://genious.sitacloud.com/icon_imagee/textInput.svg",
                "iconName": "主公，请吩咐"
              },
              "imageOCR": {
                "available": "0",
                "iconAddr": "https://genious.sitacloud.com/icon_imagee/imageOCR.svg",
                "iconName": "文字识别"
              },
              "fileupload": {
                "available": "0",
                "iconAddr": "https://genious.sitacloud.com/icon_imagee/fileupload.svg",
                "iconName": "文件"
              },
              "imageupload": {
                "available": "0",
                "iconAddr": "https://genious.sitacloud.com/icon_imagee/imageupload.svg",
                "iconName": "图片处理"
              },
              "soundupload": {
                "available": "0",
                "iconAddr": "https://genious.sitacloud.com/icon_imagee/soundupload.svg",
                "iconName": "声音分析"
              },
              "voiceInput": {
                "available": "0",
                "iconAddr": "https://genious.sitacloud.com/icon_imagee/voiceInput.svg",
                "iconName": "语音输入"
              }
            }
          }
      },
      go_home(){
    if(this.data.aiboid!="undefind"&&this.data.aiboid!=''){
       wx.redirectTo({
         url: '/pages/aibo/main/main?aiboid='+this.data.aiboid,
       })
      }else{
      wx.showToast({
        title: '关键信息缺失',
        icon:'error'
      })
      }
    },
    initHomeData(aiboID){
      var  that = this
      console.log( aiboID)
      wx.request({
        url: app.app_url.BASE_URL+app.app_url.AIBO_HOME,
        method:'POST',
        data:{
          'aiboid': aiboID,
        
        },
        success(res){
          console.log(res)
         wx.hideLoading()
    
         if(res.statusCode == 200){
           if(res.data.errorcode == 0){
            app.aibo.home = res.data.data
            that.setData({
              homedata:res.data.data
            })
            let itemData = that.loadData()
            itemData.menuName = that.data.homedata.current_aibo.aibo_name
            itemData.welcomeIntro = that.data.homedata.current_aibo.aibo_into
            that.initPage(itemData)

           
           
           }
         }
        },
        fail(res){
          console.log(res)
        }
      })
    }


})